import React, { createContext, useContext, useEffect, useState } from "react";
import { ConfigProvider, theme as antdTheme } from "antd";

const { defaultAlgorithm, darkAlgorithm } = antdTheme;

type ThemeContextType = {
  dark: boolean;
  toggle: () => void;
  setDark: (v: boolean) => void;
};

const ThemeContext = createContext<ThemeContextType>({
  dark: false,
  toggle: () => {},
  setDark: () => {},
});

function setDocumentTheme(darkMode: boolean) {
  try {
    if (darkMode) {
      document.documentElement.classList.add("dark");
      document.documentElement.setAttribute("data-theme", "dark");
      // 更新 meta theme-color（提升 Android 浏览器体验）
      const meta = document.querySelector('meta[name="theme-color"]') as HTMLMetaElement | null;
      if (meta) meta.content = "#000000";
    } else {
      document.documentElement.classList.remove("dark");
      document.documentElement.setAttribute("data-theme", "light");
      const meta = document.querySelector('meta[name="theme-color"]') as HTMLMetaElement | null;
      if (meta) meta.content = "#ffffff";
    }
  } catch (e) {
    // ignore
  }
}

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [dark, setDarkState] = useState<boolean>(false);

  // 首次读取：优先本地存储，其次使用系统 prefers-color-scheme
  useEffect(() => {
    try {
      const stored = localStorage.getItem("kale-dark-mode");
      if (stored !== null) {
        setDarkState(stored === "1");
        return;
      }

      if (window.matchMedia) {
        const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
        setDarkState(prefersDark);
        setDocumentTheme(prefersDark);
      }
    } catch (e) {
      // ignore
    }
  }, []);

  // 同步 DOM 与 localStorage
  useEffect(() => {
    try {
      setDocumentTheme(dark);
      localStorage.setItem("kale-dark-mode", dark ? "1" : "0");
    } catch (e) {
      // ignore
    }
  }, [dark]);

  // 允许外部直接设置 dark
  const setDark = (v: boolean) => setDarkState(v);
  const toggle = () => setDarkState((v) => !v);

  const themeConfig = {
    algorithm: dark ? darkAlgorithm : defaultAlgorithm,
    components: {
      Input: {
        borderRadiusLG: 3,
        activeBorderColor: "#40cfff",
        hoverBorderColor: "#40cfff",
      },
      Button: {
        colorPrimary: `#15b8f7`,
        colorPrimaryHover: "#40cfff",
        borderRadiusLG: 3,
      },
    },
  } as any;

  return (
    <ThemeContext.Provider value={{ dark, toggle, setDark }}>
      <ConfigProvider theme={themeConfig}>{children}</ConfigProvider>
    </ThemeContext.Provider>
  );
};

export const useTheme = () => useContext(ThemeContext);



